﻿using System;
using System.IO;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace SoccerSimulator5000
{
    
    public partial class FormMain : Form
    {
        public NewGameForm newGameForm;
        public static Game thisGame = new Game();
        public HomeForm homeForm;
        public StandingsForm standingsForm;
        public FixturesForm fixturesForm;
        public FinanceForm financeForm;
        public TeamForm teamForm;
        public LoadGameForm loadGameForm;
        
        
        public FormMain()
        {

            //Game.Init();

            MainMenu mainMenu = new MainMenu();
            mainMenu.ShowDialog();
            if (mainMenu.gameMode == "New")
            {
                //newGameForm = new NewGameForm();
                //newGameForm.ShowDialog();

                // attempt to solve load-issue:
                NewGameInit();

            }
            else if (mainMenu.gameMode == "Load")
            {
                //loadGameForm = new LoadGameForm();
                //loadGameForm.ShowDialog();

                // attempt to solve load-issue:
                LoadGameInit();

                //LoadSeason();

            }

            teamForm = new TeamForm();
            teamForm.UpdateDataSources();
            homeForm = new HomeForm();
            standingsForm = new StandingsForm();
            fixturesForm = new FixturesForm();
            financeForm = new FinanceForm();
            



            InitializeComponent();
            this.FormBorderStyle = FormBorderStyle.FixedDialog;

            homeTab.Controls.Add( homeForm.panel1 );
            standingsTab.Controls.Add( standingsForm.panel1 );
            fixturesTab.Controls.Add( fixturesForm.panel1 );
            financeTab.Controls.Add( financeForm.panel1 );
            teamTab.Controls.Add(teamForm.panel1);
        }



        private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            newGameForm = new NewGameForm();
            newGameForm.ShowDialog();
            teamForm.UpdateDataSources();
        }

        private void Form1_Activated(object sender, EventArgs e)
        {
            labelPlayerName.Text = Game.player.name;
            labelPlayerTeam.Text = Game.player.playerTeam.name;
            if (Game.initialized == true)
            {
                labelPlayerName.Visible = true;
                labelPlayerTeam.Visible = true;
                buttonContinue.Enabled = true;
                homeForm.panel1.Visible = true;
                fixturesForm.FillRoundsList();
                tabControl.Visible = true;
            }
            else
            {
                labelPlayerName.Visible = false;
                labelPlayerTeam.Visible = false;
                buttonContinue.Enabled = false;
                homeForm.panel1.Visible = false;
                tabControl.Visible = false;
            }
            Invalidate();
            homeForm.panel1.Invalidate();
            standingsForm.panel1.Invalidate();
            fixturesForm.panel1.Invalidate();
            financeForm.panel1.Invalidate();

        }

        private void buttonContinue_Click(object sender, EventArgs e)
        {
            // Check if season is over (year != new year)
            int year = Game.date.year;
            Game.date.Increment();
            if (year != Game.date.year)
            {
                foreach (var Team in Game.teamList)
	            {
                    Team.standingsData = new StandingsData();
	            }
                Game.season = new Season();
                Game.currentRound = 0;
                financeForm.UpdateSponsorList();
                for (int i = 0; i < Game.teamList.Count(); i++)
                {
                    Game.teamList[i].standingsData.position = i + 1;
                    Game.teamList[i].finance.sponsor = new Sponsor();
                }
                Game.season.seasonFixtures.GenerateFixtures();
            }
            this.Invalidate();

            // If current date is gameday, play matches
            foreach (var round in Game.season.seasonFixtures.fixtures)
            {
                if (round.round[0].date == Game.date)
                {
                    // Original code for manual simulation 
                    SimRoundForm simDialog = new SimRoundForm(round);
                    simDialog.ShowDialog();

                    //// Code for automatic simulation
                    //foreach (var Match in round.round)
                    //{
                    //    Match.PlayMatch();
                    //}

                }
            }

            // Perform all the weekly tasks.

            foreach (var Team in Game.teamList)
            {
                // Calculate weekly wages before deducting it from team.
                Team.CalculateSalaries();
                // Deduct money from teams for salaries and stadium upkeep.
                Team.finance.bankTotal -= Team.finance.totalSalaries;
                Team.finance.transactions.Add(new FinanceTransaction(Game.date, "Weekly Salaries", -Team.finance.totalSalaries));
                Team.finance.bankTotal -= Team.finance.stadium.totalExpencePerInc;
                Team.finance.transactions.Add(new FinanceTransaction(Game.date, "Stadium Upkeep", -Team.finance.stadium.totalExpencePerInc));

                // Deliver sponsor money to all teams.
                Team.finance.bankTotal += Team.finance.sponsor.payoutAmmount;
                Team.finance.transactions.Add(new FinanceTransaction(Game.date, "Sponsor payout", Team.finance.sponsor.payoutAmmount));

                
            }
            financeForm.UpdateDataGridView();
            financeForm.panel1.Invalidate();
            homeForm.Invalidate();
        }

        private void FormMain_Paint(object sender, PaintEventArgs e)
        {
            Game.date.Draw(500, 50, e.Graphics);
        }

        static public void Serialize( DataClass game )
        {

            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
                using (TextWriter writer = new StreamWriter(@"Xml.xml"))
                {
                    serializer.Serialize(writer, game);
                }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
            }
        }

        private void saveGameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataClass theGame = new DataClass();
            Serialize(theGame);

        }

        private void SaveSeason()
        {
            
            XmlSerializer serializer = new XmlSerializer(typeof(Season));
            using (TextWriter writer = new StreamWriter(@"Xml2.xml"))
            {
                serializer.Serialize(writer, Game.season);
            }
        }

        private void LoadSeason()
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(Season));
            using (TextReader reader = new StreamReader(@"Xml2.xml"))
            {
                Game.season = (Season)deserializer.Deserialize(reader);
            }

        }

        private void loadGameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            loadGameForm.ShowDialog();
            //XmlSerializer deserializer = new XmlSerializer(typeof(DataClass));
            //TextReader reader = new StreamReader(@"Xml.xml");

            //DataClass theGame = (DataClass)deserializer.Deserialize(reader);
            //reader.Close();

            //Game.initialized = theGame.initialized;
            //Game.player = theGame.player;
            //Game.season = theGame.season;
            //Game.schedule = theGame.schedule;
            //Game.date = theGame.date;
            //Game.teamList = theGame.teamList;
            //Game.random = theGame.random;
            //Game.previousSimSpeed = theGame.previousSimSpeed;
            //Game.currentRound = theGame.currentRound;

            //this.Activate();
        }

        // Part of attempt to solve Load-issue
        public void NewGameInit()
        {
            Game.AddTeams();

            foreach (var Team in Game.teamList)
            {
                Team.teamData.NewTeamData();
            }

            Game.player = new Player();
            Game.season = new Season();
            Game.season.Init();
            Game.schedule = new Schedule();
            Game.date = new Date();
            newGameForm = new NewGameForm();
            newGameForm.ShowDialog();
            Game.season.seasonStandings.Init();
        }

        // Part of attempt to solve load-issue
        public void LoadGameInit()
        {
            loadGameForm = new LoadGameForm();
            loadGameForm.ShowDialog();
        }


    }
}
